﻿using Model.WeiXin;
using Model.WXshopBuiness;
using Model.WXshopBuiness.DTO;
using Model.WXshopBuiness.Enum;
using Services.WeiXinProject;
using Services.WXshopBuiness;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xproject.Util;

namespace WeiXinpProAdmin.Controllers
{
    public class OrderMgrController : AdminBaseController
    {
        WXOrderServices m_WXOrderServices;
        WeiXinMessageServices m_wxmessageServices;
        UserInfoServices m_UserInfoServices;

        public OrderMgrController(WXOrderServices mWXOrderServices, WeiXinMessageServices mwxmessageServices, UserInfoServices mUserInfoServices)
        {
            m_WXOrderServices = mWXOrderServices;
            m_wxmessageServices = mwxmessageServices;
            m_UserInfoServices = mUserInfoServices;
        }

        // GET: OrderMgr
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult OrderList()
        {
            return View();
        }

        public JsonResult GetWXOrderList(int offset, int limit, string orderCode, string userCode, string mobile, int? orderState, int? orderSource, int? payType, DateTime? startTime, DateTime? endTime, string order, string ordername)
        {
            var lstRes = new List<OrderInfoModel>();
            int total = 0;
            lstRes = m_WXOrderServices.AdminGetUserOrderDetailList(Site, offset, limit, orderCode, userCode, mobile, orderState, orderSource,payType,startTime, endTime, order, ordername, out total);
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult ChangeOrderToSHIPPINGStatus(string orderId ,string kdnumber,string kdname)
        {           
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            WeiXinOrder order =  m_WXOrderServices.GetById(orderId);
            if (order != null && order.OrderState != (int)Enum_OrderState.PAYED)
            {
                result =  "订单不是已支付状态，或者已发送过了发货通知" ;
                jsonData = new { Success = success, Data = result };
            }
            WeiXinUser user = m_UserInfoServices.GetById(order.UserID);
           
            OrderChangeHistory history = new OrderChangeHistory();
            history.OrderId = order.OrderID;
            history.OrderMoney = order.OrderMoney;
            history.StateBefore = order.OrderState;
            history.StateAfter = (int)CommonHelper.GetNextOrderStatus(order.OrderState);
            history.Remarks = "微信支付完毕！订单由"+order.OrderState+" --> "+history.StateAfter;
            order.OrderState = history.StateAfter;
            order.KDCode = kdnumber;
            order.KDName = kdname;
            if (m_WXOrderServices.UpdateDBOrderInfo(order, history))
            {
                success = true;
                if (order.OrderState == (int)Enum_OrderState.SHIPPING)
                {
                    string domain = CommonHelper.GetAppSettings("Domain");
                    string url = domain + "/Order/PayOrderDetail?orderId=" + order.OrderID;
                    //发送订单已支付信息
                    m_wxmessageServices.SendOrderShippingMessage(CommonHelper.GetAppSettings("MessageSender"), "", order.UserID, user.OpenId,
                       url, CommonHelper.GetAppSettings("WeiXin_APPID"), user.NickName, order.OrderName, order.OrderCode,kdnumber,kdname);
                }
            }
            result = success ? "更新订单状态成功" : "更新订单状态失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult ChangeOrderStatus(string orderId)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            WeiXinOrder order = m_WXOrderServices.GetById(orderId);                     
            OrderChangeHistory history = new OrderChangeHistory();
            history.OrderId = order.OrderID;
            history.OrderMoney = order.OrderMoney;
            history.StateBefore = order.OrderState;
            history.StateAfter = (int)CommonHelper.GetNextOrderStatus(order.OrderState);
            history.Remarks = "微信支付完毕！订单由" + order.OrderState + " --> " + history.StateAfter;
            order.OrderState = history.StateAfter;
            result = "更新订单状态失败";
            if (m_WXOrderServices.UpdateDBOrderInfo(order, history))
            {
                result = "更新订单状态成功";
                success = true;
            }     
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult ExportOrders(string orderCode, string userCode, string mobile, int? orderState, int? orderSource, int? payType, DateTime? startTime, DateTime? endTime, string order, string ordername)
        {
            var lstRes = new List<OrderInfoModel>();
            int total = 0;
            lstRes = m_WXOrderServices.AdminGetUserOrderDetailList(Site, 0, 10000, orderCode, userCode, mobile, orderState, orderSource, payType, startTime, endTime, order, ordername, out total);
            DataTable dt= ExcelHelper.ToDataTable<OrderInfoModel>(lstRes);
            string Virbase = @"Download\Excels\";
            string DataTimeFolder = DateTime.Now.ToString("yyyyMMdd");
            string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
            string Folder = localpath + DataTimeFolder;
            if (!Directory.Exists(Folder))
                Directory.CreateDirectory(Folder);
            string ReportFileName = Folder+"\\"+DateTime.Now.ToString("yyyyMMddHHmmss") + "_out.xlsx";
            ExcelHelper.TableToExcel(dt, ReportFileName);          
            FileStream fs = new FileStream(ReportFileName, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";


            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("订单_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return new EmptyResult();
        }
    }
}